package example;

import java.util.Random;
import java.util.stream.IntStream;

public class Utils {

    private static final Random rnd = new Random();

    private Utils() {}

    public static Integer[] randomArray(int n, int bound) {
        return rnd.ints(0, bound).limit(n)
                .boxed().toArray(Integer[]::new);
    }

    public static Integer[] orderedArray(int n) {
        return IntStream.range(0, n).boxed()
                .toArray(Integer[]::new);
    }

    public static Integer[] sameArray(int n) {
        return IntStream.range(0, n).boxed()
                .map(value -> 0).toArray(Integer[]::new);
    }

    public static Random rnd() { return rnd; }

    public static <E extends Comparable<E>> void swap(E[] data, int l, int r) {
        E temp = data[l];
        data[l] = data[r];
        data[r] = temp;
    }

    public static <E extends Comparable<E>> boolean isSorted(E[] data) {
        for (int i = 1; i < data.length; i++)
            if (data[i].compareTo(data[i - 1]) < 0)
               return false;
        return true;
    }

    public static <E extends Comparable<E>> void timeSpent(SortFunction apply,
                                                           String name,  E[] data, int l, int r) {
        long start = System.nanoTime();
        apply.sort(data, l, r);
        long end = System.nanoTime();
        if (!isSorted(data)) throw new RuntimeException("排序失败");
        System.out.println(name + ", 数据规模: " + data.length + ", 耗时: " + (end - start) / 1000000000.0 + "s");
    }
}
